import os

class Program():
    def __init__(self,program,programDict):
        self.programDict=programDict
        self.program=program
        self.findProgram()
    # def startProgram_old(self):
    #     pidlist=os.popen('ps -aux | grep '+self.programDict[self.program]+"|awk '{print $2}' ").readlines()
    #     if len(pidlist) >2:
    #         return 1
    #     if self.Tag:
    #         cmd='nohup python3 '+self.programPath+self.programDict[self.program]+"main.py>>"+self.programDict[self.program]+'.log'+' 2>&1 &'
    #         os.system(cmd)
    #         print('cmd:'+cmd)
    #         return 0
    #     else:
    #         return -1
    def startProgram(self):
        if self.Tag:
            if self.programDict[self.program].open:
                return 1
            self.programDict[self.program].run()
            return 0
        else:
            return -1
    # def stopProgram_old(self):
    #     if self.Tag:
    #         pidcmd='ps -aux|grep '+self.programDict[self.program]+r"main.py|awk '{print $2}'"
    #         pid=os.popen(pidcmd).readlines(1)[0].strip()
    #         cmd='kill -9 '+pid
    #         os.system(cmd)
    #         return 0
    #     else:
    #         return -1
    def stopProgram(self):
        if self.Tag:
            if not self.programDict[self.program].open:
                return -1
            self.programDict[self.program].stop()
            return 0
    def uinstallProgram(self):
        if self.Tag:
            self.programDict.pop(self.program)
            return 0
        else:
            return -1
    def showProgram(self):
        showDict=self.programDict.copy()
        for i in self.programDict.keys():
            if self.programDict[i].open:
                showDict[i]='√'
            else:
                showDict[i]='×'
        str='=====程序列表=====\n'
        for i in showDict.keys():
            str+=(i+' : '+showDict[i]+'\n')
        str+='================'
        return str
    def findProgram(self):
        if self.program in self.programDict.keys():
            self.Tag=True
        else:
            self.Tag=False
